package com.qpf.mycms.component.email.serder.impl;

import com.qpf.mycms.component.email.properties.EmailProperties;
import com.qpf.mycms.component.email.serder.EmailSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
@EnableConfigurationProperties(EmailProperties.class) // 装载对应配置
@ConditionalOnProperty(prefix = "mycms.email", name = "enable", havingValue = "true") // 开启条件
public class EmailSenderImpl implements EmailSender {
    private EmailProperties properties;
    private JavaMailSenderImpl sender;
    @Autowired
    public EmailSenderImpl(EmailProperties properties) {
        this.properties = properties;

        sender = new JavaMailSenderImpl();
        sender.setHost(properties.getHost()); // SMTP服务器地址
        sender.setUsername(properties.getUsername()); // 邮箱用户名
        sender.setPassword(properties.getPassword()); // 邮箱密码
        sender.setDefaultEncoding("UTF-8");

        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true"); // 邮箱认证
        props.setProperty("mail.smtp.starttl.enable", "true"); // 启用TLS
        props.setProperty("mail.smtp.starttls.required", "true"); // 强制TLS
        sender.setJavaMailProperties(props);
    }
    @Override
    public void sendText(String to, String subject, String content) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setSubject(subject);
        msg.setFrom(properties.getUsername());
        msg.setTo(to);
        msg.setText(content);
        sender.send(msg);
    }
}
